package com.atguigu.gulimall.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.product.model.Category;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.mapper.CategoryMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【pms_category(商品三级分类)】的数据库操作Service实现
* @createDate 2022-03-30 15:46:30
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Resource
    CategoryMapper categoryMapper;
    @Override
    public List<Category> listWithTree() {
        //获取全部菜单
        List<Category> categoryList = categoryMapper.selectList(null);
        //获取一级菜单
        List<Category> memberList = categoryList.stream().filter(data->
                   data.getParentCid()==0
                ).map(meun->{
                    meun.setChildlist(getMeunChildList(meun,categoryList));
                    return meun;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());

        return memberList;
    }

    /**
     * 递归查找首页的数据
     * @param root
     * @param allMeun
     * @return
     */
    private List<Category> getMeunChildList(Category root,List<Category> allMeun){
      List<Category> childList =  allMeun.stream().filter(meun->
                root.getCatId()==meun.getParentCid()
        ).map(meun->{
            meun.setChildlist(getMeunChildList(meun,allMeun));
            return meun;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
       .collect(Collectors.toList());

        return childList;
    }
}




